package mvc.core;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import mvc.core.annotation.Sql;
import mvc.core.jdbc.DB;
import mvc.core.jdbc.Page;
import mvc.core.jdbc.PageData;

/**
 * Mapper的代理类
 * 
 * @author liuzy
 * @version 2.0
 * @since 2015年5月14日
 */
public class MapperProxy<T> implements InvocationHandler {
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) {
		Object result = null;
		try {
			System.out.println("代理开始---------------要开启事务");
	        String sql = method.getAnnotation(Sql.class).value().trim().toLowerCase();
	        List<Object> params = new ArrayList<>();
	        Page page = null;
	        if (args != null) {
	        	for (Object obj : args) {
	        		if (obj instanceof Page) {
	        			page = (Page) obj;
					} else {
						params.add(obj);
					}
	        	}
			}
	        String returnType = method.getReturnType().getName();
	        if (returnType.equals(PageData.class.getName())) {
	        	if (page == null)
	        		sql += " limit 1";
	        	else
	        		sql += " limit " + page.getStart() + ", " + page.getEnd();
	        	result = DB.executeQuery(sql, params);
	        } else if (returnType.equals(Integer.class.getName())) {
	        	result = DB.executeUpdate(sql, params);
	        }
	        System.out.println("代理结束---------------要提交事务");
		} catch (Exception e) {
			e.printStackTrace();
		}
        return result;
	}

}
